﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Web;
using InstaSharp.Models;
using Newtonsoft.Json.Linq;

namespace BlogsAPI.GeoLocation
{
    public class GeoGoogle : IGeoCoder
    {
        private const string ApiKey = "AIzaSyAZZqSx_t7L9cQjX8Yxymo6_XAe6s-Xycs";

        /// <summary>
        /// Получение координат по адресу
        /// </summary>
        /// <param name="address">текстовое описание места</param>
        /// <example>https://maps.googleapis.com/maps/api/geocode/json?address=Москва,+Тверская+улица,+дом+7&language=ru</example>
        /// <returns>Координаты</returns>
        public Location GetCoordsFromAddress(string address, CultureInfo lang = null, string specialApiKey = null)
        {
            Location loc = null;
            try
            {
                if (lang == null)
                {
                    lang = new CultureInfo("ru-RU");
                }
                string requesturl = String.Format("https://maps.googleapis.com/maps/api/geocode/json?address={0}&language={1}&key={2}",
                   HttpUtility.UrlEncode(address), lang.Name, specialApiKey ?? ApiKey);
                string reply = HttpClientOld.GET(requesturl);
                var data = JObject.Parse(reply);

                var geometry = data["results"][0]["geometry"]["location"];
                loc = new Location
                {
                    //У Яндекса широта и долгота изменены местами 
                    Latitude = geometry["lat"].Value<decimal>(),
                    Longitude = geometry["lng"].Value<decimal>(),
                    Name = address
                };
            }
            catch (Exception e2)
            {
                //плохо, очень плохо
                Debug.WriteLine(e2.Message);
            }
            return loc;
        }

        /// <summary>
        /// Получение имени города по координатам
        /// </summary>
        /// <param name="lat">широта</param>
        /// <param name="lng">долгота</param>
        /// <param name="lang">язык результата</param>
        /// <example>https://maps.googleapis.com/maps/api/geocode/json?latlng=55.10279%2038.753088&language=ru</example>
        /// <returns>Имя города</returns>
        public GeoResult GetCityFromCoords(double lat, double lng, CultureInfo lang = null, string specialApiKey = null)
        {
            GeoResult res = new GeoResult();
            try
            {
                if (lang == null)
                {
                    lang = new CultureInfo("ru-RU");
                }
                /////////////////////////////
                string requesturl = String.Format(new CultureInfo("en-US"),
                    "https://maps.googleapis.com/maps/api/geocode/json?latlng={0} {1}&language={2}&key={3}",
                    lat, lng, lang.Name, specialApiKey??ApiKey);//ВАЖНО - в запросе широта и долгота должны быть в порядке (долгота, широта).
                string reply = HttpClientOld.GET(requesturl);
                var data = JObject.Parse(reply);

                foreach (var row in data["results"][0]["address_components"])
                {
                    if (row["types"].Any(i => i.Value<string>() == "locality"))
                    {
                        res.City = row["short_name"].Value<string>();
                    }
                    if (row["types"].Any(i => i.Value<string>() == "country"))
                    {
                        res.CountryCode = row["short_name"].Value<string>();
                    }
                    if(!String.IsNullOrEmpty(res.City) && !String.IsNullOrEmpty(res.CountryCode))
                    {
                        break;
                    }
                }
            }
            catch (Exception e2)
            {
                //плохо, очень плохо
                Debug.WriteLine(e2.Message);
            }
            return res;
        }
    }
}
